package com.jblog.core.service.blog.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jblog.common.page.Pagination;
import com.jblog.common.page.common.PageType;
import com.jblog.core.CoreUtil;
import com.jblog.core.dao.blog.CommentDao;
import com.jblog.core.model.blog.Comment;
import com.jblog.core.model.blog.Post;
import com.jblog.core.model.blog.param.CommentParam;
import com.jblog.core.service.blog.CommentService;

@Service
public class CommentServiceImpl implements CommentService {
    
    @Autowired private CommentDao commentDao;

    @Override
    public Comment findById(Long id) {
        return findOne(new CommentParam(id));
    }
    
    public List<Comment> findByPostId(Long id) {
        return findByParam(new CommentParam(new Post(id)));
    }

    @Override
    public List<Comment> findByParam(CommentParam p) {
        return commentDao.byParam(p);
    }
    
    @Override
    @SuppressWarnings("rawtypes")
    public Pagination findByParamByPage(CommentParam p) {
        Long totalCount = count(p);
        Pagination page = new Pagination(p.getPageNo(), p.getPageSize(), totalCount, PageType.CONSECUTIVE);
        if (!StringUtils.isBlank(p.getCssClass())) {
            page.setCssClass(p.getCssClass());
        }
        if (totalCount < 1L) {
            page.setDatas(new ArrayList());
            return page;
        } 
        page.setDatas(findByParam(p));
        
        return page;
    }

    @Override
    public Long count(CommentParam p) {
        return commentDao.count(p);
    }

    private Comment findOne(CommentParam p) {
        List<Comment> es = findByParam(p);
        if (null != es && es.size() == 1) {
            return es.get(0);
        } 
        return null;
    }

    @Override
    public void enDisable(Comment e, boolean able) {
        if (!CoreUtil.checkStatus(e.getStatus(), able)) {
            update(new Comment(e.getId(), CoreUtil.toStatus(able)));
        }
    }

    @Override
    public void save(Comment e) {
        commentDao.save(e);
    }

    @Override
    public void update(Comment e) {
        commentDao.update(e);
    }
 
}